package astoliarskyi.wicket.card;

import astoliarskyi.wicket.card.Card.CardType;
import astoliarskyi.wicket.card.restriction.*;
import java.util.Calendar;

public class CardBuilder {

	private Integer id;
	private CardType cardType;
	private boolean isAccumulative;
	private Term term; 
	private TripNumber tripNumber;
	
	public CardBuilder() {

	}

	public CardBuilder id(int id) {
		this.id = id;
		return this;
	}

	public CardBuilder type(CardType cardType) {
		this.cardType = cardType;
		return this;
	}

	public CardBuilder accumulative(boolean isAccumulative) {
		this.isAccumulative = isAccumulative;
		return this;
	}

	public CardBuilder monthlyTerm(Calendar month) {
		int hasToBeFirst = month.get(Calendar.DAY_OF_MONTH);
		if (hasToBeFirst == 1) {
			term = new MonthlyTerm(month);
			return this;	
		} else {
			String errorMessage = "Calendar object for monthly term card"
					+ "has to point to 1st day of the month";
			throw new WrongCardBuilderConfiguration(errorMessage);
		}
	}
	
	public CardBuilder days10Term(Calendar startDate) {
		term = new Days10Term(startDate);
		return this;
	}

	public CardBuilder tripNumberRestriction(TripNumber.TripNumberType type) {
		tripNumber = new TripNumber(type);
		return this;
	} 

	public Card build() {
		if (id == null) {
			String errorMessage = "Card id has to be set before"
				+ " building";
			throw new WrongCardBuilderConfiguration(errorMessage);
		} else if (cardType == null) {
			String errorMessage = "Card type has to be set before"
				+ " building";
			throw new WrongCardBuilderConfiguration(errorMessage);
		}
		
		if (cardType == Card.CardType.STANDART && isAccumulative) {
			Card card = new AccumulativeCard(id);
			return card;
		} else if (isAccumulative) {
			String errorMessage = "Card type has to be STANDART to be"
				+ " accumulative";
			throw new WrongCardBuilderConfiguration(errorMessage);

		}

		if (term != null) {
			Card card = new Card(id, cardType, term);
			return card;
		} else if (tripNumber != null) {
			Card card = new Card(id, cardType, tripNumber);
			return card;
		} else {
			String errorMessage = "For this card type either term or"
				+ "trip number restriction has to be set";
			throw new WrongCardBuilderConfiguration(errorMessage);
		}
		
	}
}
